<template>
  <div class="customer-management">
    <!-- 数据管理模式切换 -->
    <el-tabs v-model="viewMode" class="view-mode-tabs">
      <el-tab-pane label="业务模式" name="business">
        <!-- 业务模式内容 -->
        <!-- 页面头部 -->
        <div class="page-header">
          <div class="header-left">
            <h1 class="page-title">客户管理</h1>
            <div class="status-badges">
              <el-tag type="primary" class="total-badge">
                <el-icon><User /></el-icon>
                客户总数: {{ stats.totalCustomers }}
              </el-tag>
              <el-tag type="success" class="active-badge">
                <el-icon><UserFilled /></el-icon>
                活跃客户: {{ stats.activeCustomers }}
              </el-tag>
              <el-tag type="warning" class="key-badge">
                <el-icon><Star /></el-icon>
                重要客户: {{ stats.keyCustomers }}
              </el-tag>
            </div>
          </div>
          
          <div class="header-actions">
            <!-- 添加提示信息 -->
            <el-alert
              title="提示：如需进行客户数据维护（新增/编辑/删除），请使用下方的数据管理模式"
              type="info"
              show-icon
              closable
              @close="handleTipClose"
              class="data-management-tip"
              v-if="showDataManagementTip"
            />
          </div>
        </div>

        <!-- 统计概览 -->
        <CustomerStats :stats="stats" />

        <!-- 筛选条件 -->
        <CustomerFilter 
          :query-params="queryParams"
          @search="handleSearch"
          @reset="handleReset"
        />

        <!-- 客户列表 -->
        <CustomerTable
          :customers="customers"
          :loading="loading"
          :pagination="pagination"
          :selected-customers="selectedCustomers"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="handleSortChange"
          @sort="handleSort"
          @view-detail="viewCustomerDetail"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @column-settings="showColumnSettings"
        />

        <!-- 客户详情对话框 -->
        <CustomerDetailDialog
          v-model="detailDialogVisible"
          :customer="detailCustomer"
          @close="handleDetailDialogClose"
        />
      </el-tab-pane>
      <el-tab-pane label="数据管理模式" name="data">
        <!-- 数据管理模式内容 -->
        <!-- 页面标题 -->
        <PageHeader 
          title="客户管理" 
          description="管理您的客户信息，进行批量导入/导出、数据清洗等数据维护操作"
          icon="User"
        />
        
        <!-- 添加提示信息 -->
        <div class="data-management-tip" v-if="showDataManagementTip">
          <el-alert
            title="提示：此页面用于批量数据维护。如需进行日常业务操作，请切换到业务模式"
            type="info"
            show-icon
            closable
            @close="handleTipClose"
          >
            <template #default>
              <div class="tip-content">
                <span>提示：此页面用于批量数据维护。如需进行日常业务操作，请前往</span>
                <el-link type="primary" @click="goToSalesManagement">销售管理 → 客户管理</el-link>
              </div>
            </template>
          </el-alert>
        </div>
        
        <!-- 智能洞察 -->
        <SmartInsights 
          v-if="stats && Object.keys(stats).length > 0"
          :insights="smartInsights"
          @action="handleInsightAction"
        />
        
        <!-- 客户统计 -->
        <CustomerStatsData 
          :stats="stats"
          :loading="loading"
        />
        
        <!-- 功能区域 -->
        <el-card class="function-area" shadow="never">
          <el-row :gutter="20">
            <el-col :span="16">
              <CustomerFilterData 
                :query-params="queryParams"
                @search="handleSearch"
                @reset="handleReset"
              />
            </el-col>
            <el-col :span="8">
              <div class="function-buttons">
                <el-dropdown trigger="click" @command="handleBatchCommand">
                  <el-button class="batch-btn">
                    批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="export">导出客户</el-dropdown-item>
                      <el-dropdown-item command="import">导入客户</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除客户</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 客户表格 -->
        <CustomerTableData
          :customers="customers"
          :loading="loading"
          :pagination="pagination"
          :selected-customers="selectedCustomers"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="handleSortChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @command="handleTableCommand"
        />
        
        <!-- 新增客户抽屉 -->
        <CustomerEditDrawer
          v-model="addDrawerVisibleData"
          form-mode="create"
          :customer-data="null"
          @submit="createCustomer"
          @close="handleAddDrawerClose"
        />
        
        <!-- 编辑客户抽屉 -->
        <CustomerEditDrawer
          v-model="editDrawerVisibleData"
          form-mode="edit"
          :customer-data="editingCustomerData"
          @submit="updateCustomer"
          @close="handleEditDrawerClose"
        />
        
        <!-- 客户详情抽屉 -->
        <CustomerDetailDrawer
          v-model="detailDrawerVisibleData"
          :customer-data="detailCustomerData"
          @edit="handleEditCustomer"
          @close="handleDetailDrawerClose"
        />
        
        <!-- 客户导入向导 -->
        <CustomerImportWizard
          v-model="importWizardVisibleData"
          @import-success="handleImportSuccess"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, UserFilled, Star, Plus
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import * as salesAPI from '@/api/sales'

// 使用路由
const router = useRouter()

// 导入拆分的组件
import CustomerStats from './components/CustomerStats.vue'
import CustomerFilter from './components/CustomerFilter.vue'
import CustomerTable from './components/CustomerTable.vue'
import CustomerDetailDialog from './components/CustomerDetailDialog.vue'

// 数据管理组件
import PageHeader from '@/components/layout/PageHeader.vue'
import SmartInsights from '@/components/insights/SmartInsights.vue'
import CustomerStatsData from '@/views/sales/customers-data-components/CustomerStats.vue'
import CustomerFilterData from '@/views/sales/customers-data-components/CustomerFilter.vue'
import CustomerTableData from '@/views/sales/customers-data-components/CustomerTable.vue'
import CustomerEditDrawer from '@/views/sales/customers-data-components/CustomerEditDrawer.vue'
import CustomerDetailDrawer from '@/views/sales/customers-data-components/CustomerDetailDrawer.vue'
import CustomerImportWizard from '@/views/sales/customers-data-components/CustomerImportWizard.vue'

// 控制提示信息显示
const showDataManagementTip = ref(true)

// 视图模式
const viewMode = ref('business')

// 跳转到销售管理
const goToSalesManagement = () => {
  router.push('/sales/customers')
}

// 跳转到销售管理
const goToDataManagement = () => {
  router.push('/sales/customers')
}

// 数据管理模式相关数据
const addDrawerVisibleData = ref(false)
const editDrawerVisibleData = ref(false)
const detailDrawerVisibleData = ref(false)
const importWizardVisibleData = ref(false)
const detailCustomerData = ref<any>(null)
const editingCustomerData = ref<any>(null)
const selectedCustomersData = ref<any[]>([])
const smartInsights = ref([])

// 智能洞察操作
const handleInsightAction = (action: string, insight: any) => {
  // 处理智能洞察操作
}

// 批量操作
const handleBatchCommand = (command: string) => {
  // 处理批量操作
}

// 表格命令
const handleTableCommand = (command: string, row: any) => {
  // 处理表格命令
}

// 创建客户
const createCustomer = async (data: any) => {
  // 创建客户
}

// 更新客户
const updateCustomer = async (data: any) => {
  // 更新客户
}

// 处理编辑客户
const handleEditCustomer = (customer: any) => {
  // 处理编辑客户
}

// 处理导入成功
const handleImportSuccess = () => {
  // 处理导入成功
}

// 处理抽屉关闭
const handleAddDrawerClose = () => {
  addDrawerVisibleData.value = false
}

const handleEditDrawerClose = () => {
  editDrawerVisibleData.value = false
}

const handleDetailDrawerClose = () => {
  detailDrawerVisibleData.value = false
}

// 关闭提示信息
const handleTipClose = () => {
  showDataManagementTip.value = false
}

// 数据模型
interface ContactPerson {
  id: number
  name: string
  department: string
  position: string
  phone: string
  email: string
  remark: string
}

interface Customer {
  id: number
  name: string
  code: string
  contactPersons: string
  status: number
  createdAt: string
  updatedAt: string
}

interface CustomerStats {
  totalCustomers: number
  newCustomers: number
  activeCustomers: number
  keyCustomers: number
  customerTrend: number
  newCustomerTrend: number
  activeCustomerTrend: number
  keyCustomerTrend: number
}

interface QueryParams {
  name: string
  contactPerson: string
  phone: string
  email: string
  status: string
  page: number
  limit: number
}

// 响应式数据
const customers = ref<Customer[]>([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const detailCustomer = ref<Customer | null>(null)
const selectedCustomers = ref<Customer[]>([])

const queryParams = reactive<QueryParams>({
  name: '',
  contactPerson: '',
  phone: '',
  email: '',
  status: '',
  page: 1,
  limit: 20
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 计算属性
const stats = computed(() => {
  return {
    totalCustomers: customers.value.length,
    newCustomers: customers.value.filter((c: Customer) => {
      // 客户模型已更改，这里需要调整逻辑
      return false; // 暂时返回false，后续根据实际需求调整
    }).length,
    activeCustomers: customers.value.filter((c: Customer) => c.status === 1).length,
    keyCustomers: 0, // 客户模型已更改，这里需要调整逻辑
    customerTrend: 0,
    newCustomerTrend: 0,
    activeCustomerTrend: 0,
    keyCustomerTrend: 0
  }
})

// 方法
const loadCustomers = async () => {
  loading.value = true
  try {
    // 构造API查询参数
    const params: any = {
      name: queryParams.name || undefined,
      contactPerson: queryParams.contactPerson || undefined,
      phone: queryParams.phone || undefined,
      email: queryParams.email || undefined,
      page: queryParams.page,
      limit: queryParams.limit
    }
    
    // 只有当status不为空时才添加到参数中
    if (queryParams.status) {
      params.status = parseInt(queryParams.status)
    }
    
    // 调用真实API
    const response = await salesAPI.getCustomers(params)
    
    if (response.data) {
      customers.value = response.data.list
      pagination.total = response.data.pagination.total
    }
    
    // 更新统计信息
    // stats.totalCustomers = response.stats.total
    // stats.activeCustomers = response.stats.active
  } catch (error) {
    console.error('加载客户列表失败:', error)
    ElMessage.error('加载客户列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const viewCustomerDetail = (customer: Customer) => {
  detailCustomer.value = customer
  detailDialogVisible.value = true
}

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  detailCustomer.value = null
}

const handleSearch = () => {
  ElMessage.info('筛选客户')
  loadCustomers()
}

const handleReset = () => {
  Object.assign(queryParams, {
    name: '',
    contactPerson: '',
    phone: '',
    email: '',
    status: '',
    page: 1,
    limit: 20
  })
  loadCustomers()
}

const handleSelectionChange = (selection: Customer[]) => {
  selectedCustomers.value = selection
}

const handleRowClick = (row: Customer) => {
  viewCustomerDetail(row)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  ElMessage.info(`按 ${sort.prop} ${sort.order} 排序`)
}

const handleSort = (field: string) => {
  ElMessage.info(`按 ${field} 排序`)
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  loadCustomers()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadCustomers()
}

const handleQueryParamsUpdate = (newParams: QueryParams) => {
  Object.assign(queryParams, newParams);
}

const showColumnSettings = () => {
  ElMessageBox.alert('列设置功能待实现', '提示', {
    confirmButtonText: '确定'
  })
}

// 生命周期
onMounted(() => {
  loadCustomers()
})
</script>